import axios from 'axios'
import { Toast } from 'antd-mobile';
import { createBrowserHistory } from 'history';
const history = createBrowserHistory();
// 请求拦截
axios.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
})

// 回调拦截
axios.interceptors.response.use(res => { // 401的情况下表示验证未通过直接到error
  const status = Number(res.status) || 200
  //const message = res.data.msg || '未知错误'
  const urlWhiteList = [
    '/api/root/code'
  ]
  // 如果是白名单类型放入catch自行处理
  if (status !== 200) return Promise.reject(res)
  // 如果statusCode为200且res.code为200则放过，否者默认统一处理
  if ((status !== 200 || (status === 200 && res.data.code !== 200)) && !urlWhiteList.includes(res.config.url)) {
    // return Promise.reject(new Error(message))
    history.push('/');
    Toast.offline('Network connection failed !!!', 1)
  } else {
    return res
  }
}, error => {
  if (error.response.status === 401) {
    history.push('/');
    Toast.offline('Network connection failed !!!', 1)
  }
  return Promise.reject(new Error(error))
})

export default axios
